# ipython 中可用魔术犯法 %matplotlib inline

# pycharm 中必须使用plt.show()

import matplotlib.pyplot as plt
import numpy as np

plt.style.use("seaborn-whitegrid")

# x=[1,2,3,4]
# y=[2,4,9,16]
#
# # print(plt.style.available[:5])
#
# plt.plot(x,y)
# plt.ylabel("squares")
# plt.show()


# 将图像保存为文件
# import numpy as np
# x= np.linspace(0,10,100)
# plt.plot(x,np.exp(x))
# plt.show()
# plt.savefig("my_pic.png")


# 1.折线图
x = np.linspace(0, 2 * np.pi, 100)
# plt.plot(x,np.sin(x))
# plt.plot(x,np.cos(x))
# plt.show()

# 调整线条颜色和风格
# 调整线条颜色
# offsets = np.linspace(0, np.pi, 5)
# colors = ["blue", "g", "r", "yellow", "pink"]
# for offset, color in zip(offsets, colors):
#     plt.plot(x, np.sin(x - offset), color=color)
# plt.show()

# 调整线条风格
# x=np.linspace(0,10,11)
# offsets=list(range(8))
# linestyles=["solid","dashed","dashdot","dotted","-","--","-.",":"]
# for offset,linestyle in zip(offsets,linestyles):
#     plt.plot(x,x+offset,linestyle=linestyle)
# plt.show()

# 调整线宽
# x=np.linspace(0,10,11)
# offsets=list(range(0,12,3))
# linewidths=(i*2 for i in range(1,5))
# for offset,linewidth in zip(offsets,linewidths):
#     plt.plot(x,x+offset,linewidth=linewidth)
# plt.show()


# 调整数据点标记
# x=np.linspace(0,10,11)
# offsets=list(range(0,12,3))
# marks=["*","+","o","s"]
# for offset,marker in zip(offsets,marks):
#     # plt.plot(x,x+offset,marker=marker)
#     plt.plot(x,x+offset,marker=marker,markersize=10)
# plt.show()

# 颜色跟风格设置的简写
# x=np.linspace(0,10,11)
# offsets=list(range(0,8,2))
# color_linestyles=["g-","c--","k-.","r:"]
# for offset,color_linestyle in zip(offsets,color_linestyles):
#     plt.plot(x,x+offset,color_linestyle)
# plt.show()

# x=np.linspace(0,10,11)
# offsets=list(range(0,8,2))
# corlor_marker_linestyles=["g*-","c+--","ko-.","rs:"]
# for offset,corlor_marker_linestyle in zip(offsets,corlor_marker_linestyles):
#     plt.plot(x,x+offset,corlor_marker_linestyle)
# plt.show()


# 2.调整坐标轴
# xlim,ylim
# x=np.linspace(0,2*np.pi,100)
# plt.plot(x,np.sin(x))
# plt.xlim(-1,7)
# plt.ylim(-1.5,1.5)
# plt.show()

# axis
# x=np.linspace(0,2*np.pi,100)
# plt.plot(x,np.sin(x))
# plt.axis([-2,8,-2,2])
# plt.show()
#
# x=np.linspace(0,2*np.pi,100)
# plt.plot(x,np.sin(x))
# plt.axis("tight")
# plt.show()

# x=np.linspace(0,2*np.pi,100)
# plt.plot(x,np.sin(x))
# plt.axis("equal")
# plt.show()

# ?plt.axis


# 对数坐标
# x=np.logspace(0,5,100)
# plt.plot(x,np.log(x))
# plt.xscale("log")
# plt.show()


# 调整坐标轴刻度
# x=np.linspace(0,10,100)
# plt.plot(x,x**2)
# plt.xticks(np.arange(0,12,step=1))
# plt.show()

# x=np.linspace(0,10,100)
# plt.plot(x,x**2)
# plt.show()

# x=np.linspace(0,10,100)
# plt.plot(x,x**2)
# plt.xticks(np.arange(0,12,step=1),fontsize=15)
# plt.yticks(np.arange(0,100,step=10))
# plt.show()

# 调整刻度样式
# x=np.linspace(0,10,100)
# plt.plot(x,x**2)
# plt.tick_params(axis="both",labelsize=15)
# plt.show()

# 设置图形标签
# x=np.linspace(0,2*np.pi,100)
# plt.plot(x,np.sin(x))
# plt.title("A since Curve",fontsize=20)
# plt.xlabel("x",fontsize=15)
# plt.ylabel("sin(x)",fontsize=15)
# plt.show()

# 设置图例
# x=np.linspace(0,2*np.pi,100)
# plt.plot(x,np.sin(x),"b--",label="Sin")
# plt.plot(x,np.cos(x),"r--",label="Cos")
# plt.legend()
# plt.show()

# x=np.linspace(0,2*np.pi,100)
# plt.plot(x,np.sin(x),"b--",label="Sin")
# plt.plot(x,np.cos(x),"r--",label="Cos")
# plt.ylim(-1.5,2)
# plt.legend(loc="upper center",frameon=True,fontsize=15)
# plt.show()

# 添加文字和箭头
# 添加文字
# x=np.linspace(0,2*np.pi,100)
# plt.plot(x,np.sin(x),"b--")
# plt.text(3.5,0.5,"y=sin(x)",fontsize=15)
# plt.show()

# 添加箭头
# x=np.linspace(0,2*np.pi,100)
# plt.plot(x,np.sin(x),"b--")
# plt.annotate("local min",xy=(1.5*np.pi,-1),xytext=(4.5,0)
#              ,arrowprops=dict(facecolor='black',shrink=0.1))
# plt.show()


# 2.散点图
# 简单散点图
# x=np.linspace(0,2*np.pi,20)
# plt.scatter(x,np.sin(x),marker='o',s=30,c='r')  #s 大小，c颜色
# plt.show()


# 颜色配置
# x=np.linspace(0,10,100)
# y=x**2
# plt.scatter(x,y,c=y,cmap="Blues")
# plt.colorbar()
# plt.show()

# 根据数据控制点的大小
# x,y,colors,size=(np.random.rand(100) for i in range(4))
# plt.scatter(x,y,c=colors,s=1000*size,cmap="viridis")
# plt.show()

# 透明度
# x,y,colors,size=(np.random.rand(100) for i in range(4))
# plt.scatter(x,y,c=colors,s=1000*size,cmap="viridis",alpha=0.3)
# plt.show()


# 随机漫步
# from random import choice
#
#
# class RandomWalk():
#     """
#     一个生产随机漫步的类
#     """
#
#     def __init__(self, num_points=5000):
#         self.num_points = num_points
#         self.x_values = [0]
#         self.y_values = [0]
#
#     def fill_walk(self):
#         while len(self.x_values) < self.num_points:
#             x_direction = choice([1, -1])
#             x_distance = choice([0, 1, 2, 3, 4])
#             x_step = x_direction * x_distance
#
#             y_direction = choice([1, -1])
#             y_distance = choice([0, 1, 2, 3, 4])
#             y_step = y_direction * y_distance
#
#             if x_step == 0 or y_step == 0:
#                 continue
#             next_x = self.x_values[-1] + x_step
#             next_y = self.y_values[-1] + y_step
#
#             self.x_values.append(next_x)
#             self.y_values.append(next_y)
#
# rw=RandomWalk(10000)
# rw.fill_walk()
# point_numbers=list(range(rw.num_points))
# plt.figure(figsize=(12,6))
# plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap="inferno",s=1)
# plt.colorbar()
# plt.scatter(0,0,c="green",s=100)
# plt.scatter(rw.x_values[-1],rw.y_values[-1],c="red",s=100)
# plt.xticks([])
# plt.yticks([])
#
# plt.show()


# 3.柱状图
# 简单柱形图
# x=np.arange(1,6)
# plt.bar(x,x*2,align="center",width=0.5,alpha=0.5,color="yellow",edgecolor="red")
# plt.xticks(x,("G1","G2","G3","G4","G5"))
# plt.tick_params(axis="both",labelsize=13)
# plt.show()

# x=["G"+str(i) for i in range(5)]
# y=1/(1+np.exp(-np.arange(5)))
# colors=["red","yellow","blue","green","gray"]
# plt.bar(x,y,align="center",width=0.5,alpha=0.5,color=colors)
# plt.tick_params(axis="both",labelsize=13)
# plt.show()

# 累加柱形图
# x=np.arange(5)
# y1=np.random.randint(20,30,size=5)
# y2=np.random.randint(20,30,size=5)
# plt.bar(x,y1,width=0.5,label="man")
# plt.bar(x,y2,width=0.5,bottom=y1,label="women")
# plt.legend()
# plt.show()

# 并列柱形图
# x=np.arange(15)
# y1=x+1
# y2=y1+np.random.random(15)
# plt.bar(x,y1,width=0.3,label="man")
# plt.bar(x+0.3,y2,width=0.3,label="women")
# plt.legend()
# plt.show()


# 横向柱形图
# x=["G1","G2","G3","G4","G5"]
# y=2*np.arange(1,6)
# plt.barh(x,y,align="center",height=0.5,alpha=0.8,color="blue",edgecolor="red")
# plt.tick_params(axis="both",labelsize=13)
# plt.show()


# 4.多子图
# 简单多子图
# 简单多子图
# def f(t):
#     return np. exp (-t) * np. cos (2*np. pi*t)
#
# t1 = np. arange (0.0, 5.0, 0.1)
# t2 = np. arange (0.0, 5.0, 0.02)
#
# plt. subplot (211)
# plt. plot (t1, f(t1), "bo-", markerfacecolor="r", markersize=5)
# plt. title ("A tale of 2 subplots")
# plt. ylabel ("Damped oscillation")
#
# plt. subplot (212)
# plt. plot (t2, np. cos (2*np. pi*t2), "r--")
# plt. xlabel ("time (s)")
# plt. ylabel ("Undamped")
# plt.show()


# #多行多列子图
# x = np. random. random (10)
# y = np. random. random (10)
#
# plt. subplots_adjust(hspace=0.5, wspace=0.3)
#
# plt. subplot (321)
# plt. scatter(x, y, s=80, c="b", marker=">")
#
# plt. subplot (322)
# plt. scatter (x, y, s=80, c="g", marker="*")
#
# plt. subplot (323)
# plt. scatter (x, y, s=80, c="r", marker="s")
#
# plt. subplot (324)
# plt. scatter (x, y, s=80, c="c", marker="p")
#
# plt. subplot (325)
# plt. scatter (x, y, s=80, c="m", marker="+")
#
# plt. subplot (326)
# plt. scatter (x, y, s=80, c="y", marker="H")
#
# plt.show()


# 不规则多子图
# def f(x):
#     return np. exp (-x) *np. cos (2*np. pi*x)
#
# x = np. arange (0.0, 3.0, 0.01)
# grid = plt. GridSpec (2, 3, wspace=0.4, hspace=0.3)
#
# plt. subplot (grid[0, 0])
# plt. plot (x, f(x))
#
# plt. subplot (grid[0, 1:])
# plt. plot (x, f(x), "r--", lw=2)
#
# plt. subplot (grid[1, :])
# plt. plot (x, f(x), "g-,", lw=3)

# 5、直方图

# 普通频次直方图
# mu, sigma= 100, 15
# x=mu + sigma *np. random. randn (10000)
#
# plt. hist (x, bins=50, facecolor='g', alpha=0.75)

# # 概率密度 density= True 求概率密度
# # histtype='step' 求空心图
# mu, sigma = 100, 15
# x=mu + sigma * np. random. randn (10000)
# plt. hist(x, 50, density=True, color="r")
# plt. xlabel ('Smarts')
# plt. ylabel ('Probability')
# plt. title('Histogram of IQ')
# plt. text (60, .025, r'$\mu=100, \ \sigma=15s')
# plt. xlim(40, 160)
# plt. ylim(0, 0.03)

# from scipy. stats import norm
# mu, sigma = 100, 15
# x=mu + sigma * np. random. randn (10000)
#
# _, bins, __= plt. hist(x, 50, density=True)
# y = norm. pdf (bins, mu, sigma)
# plt. plot (bins, y, 'r--', lw=3)
# plt. xlabel ('Smarts')
# plt. ylabel ('Probability')
# plt. title('Histogram of IQ')
# plt. text (60, .025, r' $\mu=100, \ \sigma=15$')
# plt. xlim(40, 160)
# plt. ylim(0, 0.03)

# 累计概率分布 cumulative
# mu, sigma = 100, 15
# x=mu + sigma * np. random. randn (10000)
#
# plt. hist (x, 50, density=True, cumulative=True, color="r")
# plt. xlabel ('Smarts')
# plt. ylabel ('Cum_Probability')
# plt. title('Histogram of IQ')
# plt. text (60, 0.8, r'$\mu=100, \ \sigma=158')
# plt. xlim (50, 165)
# plt. ylim(0, 1.1)
#

# 基本误差图 errorbar
# x= np. linspace (0, 10 , 50)
# dy=0.5
# y = np. sin(x) + dy*np. random. randn (50)
# plt. errorbar (x, y , yerr=dy, fmt="+b")


# 柱形图误差图 yerr代表误差
# menMeans = (20, 35, 30, 35, 27)
# womenMeans = (25, 32, 34, 20, 25)
# menStd = (2, 3, 4, 1, 2)
# womenStd = (3, 5, 2, 3, 3)
# ind =['GI', 'G2', 'G3', 'G4', 'G5']
# width = 0.35
#
# p1 = plt. bar (ind, menMeans, width=width, label="Men", yerr=menStd)
# p2 = plt. bar (ind, womenMeans, width=width, bottom=menMeans, label="Women", yerr=womenStd)
#
# plt. ylabel ('Scores')
# plt. title('Scores by group and gender')
# plt. yticks (np. arange (0, 81, 10))
# plt. legend ()


# 面向对象的风格简介
# #普通图
# x = np. linspace (0, 5, 10)
# y=x**2
#
# fig = plt. figure (figsize=(8, 4), dpi=80) #图像
# axes = fig. add_axes ([0.1, 0.1, 0.8, 0.8]) #轴left, bottom, width, height (range 0 to 1)
# axes. plot (x, y, 'r')
# axes. set_xlabel ('x')
# axes. set_ylabel ('y')
# axes. set_title ( 'title')


# #画中画
# x=np. linspace (0, 5, 10)
# y=x**2
# fig = plt. figure()
#
# ax1 = fig. add_axes ([0.1, 0.1, 0.8, 0.8])
# ax2 = fig. add_axes ([0.2, 0.5, 0.4, 0.3])
#
# ax1. plot (x, y, 'r')
#
# ax1. set_xlabel ('x')
# ax1. set_ylabel ('y')
# ax1. set_title('title')
#
# ax2. plot (y, x, 'g')
# ax2. set_xlabel ('y')
# ax2. set_ylabel ('x')
# ax2. set_title('insert title')


# 多子图
# def f(t):
#     return np. exp(-t) *np. cos (2*np. pi*t)
# t1 = np. arange (0.0, 3.0, 0.01)
# fig= plt. figure()
# fig. subplots_adjust (hspace=0.4, wspace=0.4)
#
# ax1 = plt. subplot (2, 2, 1)
# ax1. plot (t1, f(t1))
# ax1. set_title ("Upper left")
#
# ax2 = plt. subplot (2, 2, 2)
# ax2. plot (t1, f(t1))
# ax2. set_title ("Upper right")
#
# ax3 = plt. subplot (2, 1, 2)
# ax3. plot (t1, f(t1))
# ax3. set_title ("Lower")


# 了解matpotlib三维图像的绘制
# 三维数据点与线
# from mpl_toolkits import mplot3d
#
# ax = plt. axes (projection="3d")
# zline =np. linspace (0, 15, 1000)
# xline =np. sin(zline)
# yline =np. cos (zline)
# ax. plot3D (xline, yline, zline)
#
# zdata =15*np. random. random (100)
# xdata = np. sin (zdata)
# ydata = np. cos (zdata)
# ax. scatter3D (xdata, ydata , zdata, c=zdata, cmap="spring")

# 三维数据曲面图
# def f(x, y):
#     return np. sin(np. sqrt(x**2 + y**2))
# x=np. linspace(-6, 6, 30)
# y = np. linspace(-6, 6, 30)
# X, Y=np. meshgrid(x, y)
# Z=f(X, Y)
#
# ax = plt. axes (projection="3d")
# ax. plot_surface (X, Y, Z, cmap="viridis")


# 了解基于matplotlib的高级版本seabon库
# Seaborn库-文艺青年的最爱
'''
Seabrn与Matplotlib
Seaborn是一个基于matplotib且数据结构与pandas统一的统计图制作库
'''

# x =np. linspace (0, 10, 500)
# y= np. cumsum (np. random. randn (500, 6), axis=0)
# with plt. style. context ("classic"):
#     plt. plot (x, y)
#     plt. legend ("ABCDEF", ncol=2, loc="upper left")


# import seaborn as sns
# x=np. linspace (0, 10, 500)
# y= np. cumsum (np. random. randn (500, 6), axis=0)
# sns. set ()
# plt. plot(x, y)
# plt. legend ("ABCDEF", ncol=2, loc="upper left")


# 柱形图的对比
# x= ['GI', 'G2', 'G3', 'G4', 'G5']
# y = 2 * np. arange (1, 6)
#
# plt. figure (figsize=(8, 4))
# plt. barh(x, y, align="center", height=0.5, alpha=0.8, color="blue")
# plt. tick_params (axis="both", labelsize=13)

import seaborn as sns

#
# x=['G5', 'G4', 'G3', 'c2', 'G1']
# y = 2* np. arange (5, 0, -1)
# #sns. barplot (y, x)
# sns. barplot (y, x, linewidth=5)

# 以莺尾花数据集为例 pairplot
# iris = sns.load_dataset("iris")
# sns.pairplot(data=iris, hue="species")
#
# plt.show()

# 了解Pandas类型数据绘制图形的直接方法
# Pandas中的绘图函数概览
# 线形图
# import pandas as pd
#
# df = pd.DataFrame(np.random.randn(1000, 4).cumsum(axis=0),
#                   columns=list("ABCD"),
#                   index=np.arange(1000))
# df.plot()
#
# #多组数据竖图
# df2. plot. bar()
#
# #多组数据累加竖图
# df2. plot. bar(stacked=True)
#
# #多组数据累加横图
# df2. plot. barh (stacked=True)
#
# #直方图和密度图
# df4 = pd. DataFrame ({"A": np. random. randn (1000) +3, "B": np. random. randn (1000), "C": np. random. randn (1000) -3})
# df4. head()
#
# #普通直方图
# df4. plot. hist (bins=20)
#
# #累加直方图
# df4['A']. plot. hist (cumulative=True)
#
#
# #概率密度图
# df4['A' ]. plot (kind="kde")
#
#
# #散点图
# housing = pd. read_csv ("housing.csv")
# housing. head ()
#
# #圆的半价大小代表每个区域人口数量(s),颜色代表价格(c),用预定义的jet表进行可视化
# with sns. axes_style ("white"):
#     housing. plot (kind="scatter", x="longitude", y="latitude", alpha=0.6,
#         s=housing ["population"]/100, label="population",
#         c="median_house_value", cmap=plt. get_cmap ("jet"), colorbar=True)
# plt. legend()
# plt. axis ([-125, -113.5, 32, 43])
#
# housing. plot (kind="scatter", x="median_income", y="median_house_value", alpha=0.8)
#
# #多子图
# df = pd. DataFrame (np. random. randn (1000, 4).cumsum (axis=0),
#                     columns=list ("ABCD"), index=np. arange (1000))
# df. head()
#
# #默认情形
# df. plot (subplots=True, figsize=(6, 16))
#
# #设定图形安排
# df. plot (subplots=True, layout=(2, 2), figsize=(16, 6), sharex=False)